package com.cg.design.graphicdesignpattern.builder;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Builder的子类，使用HTML编写文档，其返回结果是HTML文件的名字
 *
 * @program: LeetCode->HTMLBuilder
 * @description: Builder的子类，使用HTML编写文档，其返回结果是HTML文件的名字
 * @author: cg
 * @create: 2022-03-20 21:10
 **/
public class HTMLBuilder extends Builder {

    /**
     * 文件名
     */
    private String fileName;
    /**
     * 用于编写文件的PrintWriter
     */
    private PrintWriter writer;

    @Override
    protected void buildTitle(String title) {
        fileName = title + ".html";
        try {
            // 生成PrintWriter
            writer = new PrintWriter(new FileWriter(fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.println("<html>\n\t<head>\n\t\t<title>" + title + "</title>\n\t</head>\n\t<body>");
        writer.println("\t\t<h1>" + title + "</h1>");
    }

    @Override
    protected void buildString(String string) {
        writer.println("\t\t<p>" + string + "</p>");
    }

    @Override
    protected void buildItems(String[] items) {
        writer.println("\t\t<ul>");
        for (int i = 0; i < items.length; i++) {
            writer.println("\t\t\t<li>" + items[i] + "</li>");
        }
        writer.println("\t\t</ul>");
    }

    @Override
    protected void buildDone() {
        writer.println("\t</body>\n</html>");
        writer.close();
    }

    public String getResult() {
        return fileName;
    }

}
